import { Consts, createAPI } from './fetchRequest';

// export const GET = 'get';
// export const POST = 'post';
// export const PUT = 'put';//更新
// export const PATCH = 'patch';//局部更新
// export const DELETE = 'delete';
// export const HEAD = 'head';

function createUrl(apiCode) {
  // return `${HOST}/${apiCode}`;
  return `http://devtalapi.shishike.com/${apiCode}`;
}

function filterNullAndUndefined(obj) {
  if (obj && !Array.isArray(obj)) {
    const ret = {};
    Object.keys(obj).forEach((key) => {
      const val = obj[key];
      if (val !== null && val !== undefined) {
        ret[key] = val;
      }
    });
    return ret;
  }
  return obj;
}

function createOptions(params) {
  const param = filterNullAndUndefined(params);
  return {
    mode: 'cors',
    credentials: 'include',
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
    },
    body: {
      ...param,
    },
  };
}
function createJsonOptions(params) {
  const param = filterNullAndUndefined(params);
  return {
    mode: 'cors',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      'X-Requested-With': 'XMLHttpRequest',
    },
    body: JSON.stringify(param),
  };
}
// 获取资源
export function createGetAPI(apiCode, params) {
  return createAPI(Consts.HttpMethods.GET, createUrl(apiCode), createOptions(params));
}
// 删除资源
export function createDeleteAPI(apiCode, params) {
  return createAPI(Consts.HttpMethods.DELETE, createUrl(apiCode), createOptions(params));
}
// 新建资源或更新资源
export function createPostAPI(apiCode, params) {
  return createAPI(Consts.HttpMethods.POST, createUrl(apiCode), createOptions(params));
}
export function createPostJsonAPI(apiCode, params) {
  return createAPI(Consts.HttpMethods.POST, createUrl(apiCode), createJsonOptions(params));
}
// 更新资源
export function createPutAPI(apiCode, params) {
  return createAPI(Consts.HttpMethods.PUT, createUrl(apiCode), createOptions(params));
}
export function createPutJsonAPI(apiCode, params) {
  return createAPI(Consts.HttpMethods.PUT, createUrl(apiCode), createJsonOptions(params));
}
// 局部更新资源
export function createPatchAPI(apiCode, params) {
  return createAPI(Consts.HttpMethods.PATCH, createUrl(apiCode), createOptions(params));
}
export function createPatchJsonAPI(apiCode, params) {
  return createAPI(Consts.HttpMethods.PATCH, createUrl(apiCode), createJsonOptions(params));
}
